package cn.tedu.cwfw.base.interceptor;


import cn.tedu.cwfw.base.response.JsonResult;
import cn.tedu.cwfw.base.response.StatusCode;
import cn.tedu.cwfw.client.util.JWTUtil;
import cn.tedu.cwfw.client.util.JwtConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;


/**
 * @author Kiven
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader(JwtConstants.AUTHORIZATION);
        if("OPTIONS".equals(request.getMethod())){
            return true;
        }

        if(!StringUtils.isBlank(header)){
           String token = header.substring(JwtConstants.AUTHORIZATION_BEARER.length(),header.length());
           try{
               JWTUtil.verify(token);
           } catch (Exception e){
               response.setContentType("application/json;charset=utf-8");
               response.setStatus(200);
               response.getWriter().write(JSON.toJSONString(new JsonResult(StatusCode.TIMEOUT_LOGIN.getCode(),"登录已过期，请重新登录")));
           }

            return true;
        }

        response.setContentType("application/json;charset=utf-8");
        response.setStatus(200);
        response.getWriter().write(JSON.toJSONString(new JsonResult(StatusCode.NOT_LOGIN.getCode(),"请登录")));
        return false;
    }
}
